package com.yanqu.road.dao.impl.admin;

import com.yanqu.road.dao.db.DbNameStrategy;
import com.yanqu.road.dao.db.DbParameter;
import com.yanqu.road.dao.impl.TempDataObjectDao;
import com.yanqu.road.entity.admin.AdminInnerBuyOrderData;
import com.yanqu.road.utils.date.DateHelper;

import java.sql.CallableStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class AdminInnerBuyOrderDataDaoImpl extends TempDataObjectDao<AdminInnerBuyOrderData> {

    public Map<String, AdminInnerBuyOrderData> getLastAdminInnerBuyOrderData() {
        ResultSet rs = null;
        CallableStatement call = null;
        String getAdminInnerBuyOrderDataSql = "select * from `t_s_inner_user_buy_order` where `orderTime`>=?";
        Map<String, AdminInnerBuyOrderData> result = new ConcurrentHashMap<>();
        try {
            getDb().setConnName(DbNameStrategy.getServerDb());
            call = getDb().getConnection().prepareCall(getAdminInnerBuyOrderDataSql);
            int i = 1;
            call.setLong(i++, DateHelper.getTodayZeroTimeStamp() - DateHelper.DAY_MILLIONS * 7);
            rs = call.executeQuery();
            while (rs.next()) {
                AdminInnerBuyOrderData data = parseData(rs);
                result.put(data.getOrderId(), data);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);} finally {
            getDb().closeConnection(call, rs);
        }
        return result;
    }

    public static String insertAdminInnerBuyOrderDataSql = "insert into `t_s_inner_user_buy_order`(orderId,orderTime) values (?,?)";
    @Override
    protected boolean addData(AdminInnerBuyOrderData adminInnerBuyOrderData) {
        adminInnerBuyOrderData.setBeginWriteTime();
        getDb().setConnName(DbNameStrategy.getServerDb());
        int i = 1;
        Map<Integer, DbParameter> para = new HashMap<Integer, DbParameter>();
        para.put(i++, new DbParameter(Types.VARCHAR, adminInnerBuyOrderData.getOrderId()));
        para.put(i++, new DbParameter(Types.BIGINT, adminInnerBuyOrderData.getOrderTime()));
        if (getDb().executeNoneQuery(insertAdminInnerBuyOrderDataSql, para) > 0) {
            return true;
        }
        return false;

    }


    @Override
    protected boolean updateData(AdminInnerBuyOrderData adminInnerBuyOrderData) {

        return true;
    }


    @Override
    protected AdminInnerBuyOrderData parseData(ResultSet rs) throws SQLException {
        AdminInnerBuyOrderData adminInnerBuyOrderData = new AdminInnerBuyOrderData();
        adminInnerBuyOrderData.setOrderId(rs.getString("orderId"));
        adminInnerBuyOrderData.setOrderTime(rs.getLong("orderTime"));

        return adminInnerBuyOrderData;
    }
}
